package com.frx.datastruct.chapterfour;

import com.frx.datastruct.chapterthree.Queue;

/**
 * @author ：frx
 * @date ：Created in 2019/2/18 21:39
 * @description： 改进链表，加入tail节点，从head节点删除元素容易，所以队列的实现中head节点作为队首，用于出队删除元素
 *  *                从tail节点添加元素容易，所以tail节点作为队尾，用于入队
 * @modified By：
 * @version: ToDO
 */
public class LinkedListQueue<E> implements Queue<E > {


    /** 使用一个内部类Node*/
    private class  Node{
        public E e;
        public Node next;

        public Node(E e,Node next){
            this.e = e;
            this.next = next;
        }
        public Node(E e){
            this(e,null);
        }
        public Node(){
            this(null,null);
        }

        @Override
        public String toString(){
            return e.toString();
        }
    }

    /** 维护一个头节点和尾节点*/
    private Node head,tail;
    private int size;

    public LinkedListQueue(){
        head = null;
        tail = null;
        size = 0;
    }








    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void enqueue(E e) {

        if(tail == null){
             tail = new Node(e);
             head = tail;
        }else {
            tail.next = new Node(e);
            tail = tail.next;
        }
        size++;
    }

    /** 出队操作，从队首出队*/
    @Override
    public E dequeue() {
        if(isEmpty()){
            throw new IllegalArgumentException("Dequeue failed,queue is empty!");
        }
        Node retNode = head;
        head = head.next;
        retNode.next = null;
        /** 如果出队之后队列为空，tail也要为空*/
        if(head == null){
            tail = null;
        }
        size--;
        return retNode.e;
    }

    @Override
    public E getFront() {
        if(isEmpty()){
            throw new IllegalArgumentException("Queue is empty!");
        }
        return head.e;
    }

    @Override
    public String toString(){

        StringBuilder res = new StringBuilder();
        res.append("Queue : front");
        Node cur = head;
        while (cur != null){
            res.append(cur.e + "->");
            cur = cur.next;
        }
        res.append("NULL tail");
        return res.toString();
    }
}
